<!-- src/components/CommentItem.vue -->
<template>
  <a-comment
    :author="comment?.userName"
    :avatar="comment?.userAvatar"
    :style="{ marginLeft: depth * 24 + 'px' }"
  >
    <template #content>
      <p>{{ comment.content }}</p>
    </template>
    <template #actions>
      <span @click="toggleLocalReply">回复</span><span v-if="loginUserStore.loginUser?.id === comment.userId "
                                                       @click="deleteReply" style="color: red;">删除</span>
    </template>
    <template #datetime>
      <a-tooltip :title="comment.updateTime">
        <span>{{ comment.updateTime }}</span>
      </a-tooltip>
    </template>

    <!-- 回复输入框 -->
    <div v-if="localReplyState" class="reply-box">
      <a-comment>
        <template #avatar>
          <a-avatar :src="loginUserStore.loginUser?.userAvatar" />
        </template>
        <template #content>
          <a-form-item>
            <a-textarea :rows="1" v-model:value="commentContent" />
          </a-form-item>
          <a-form-item>
            <a-button
              type="primary"
              size="small"
              @click="addComment"
            >
              提交回复
            </a-button>
          </a-form-item>
        </template>
      </a-comment>
    </div>

    <!-- 递归子评论 -->
    <template v-if="comment.children?.length">
      <comment-item
        v-for="child in comment.children"
        :key="child.id"
        :comment="child"
        :depth="depth + 1"
      />
    </template>
  </a-comment>
</template>

<script setup lang="ts">
import { inject, type Ref, ref, watch } from 'vue'
import { useLoginUserStore } from '@/stores/useLoginUserStore.ts'
import { message } from 'ant-design-vue'
import { createCommentUsingPost, deleteCommentUsingPost } from '@/api/commentController.ts'


const props = defineProps<{
  comment: API.CommentVO
  depth: number
}>()

const loginUserStore = useLoginUserStore()
const localReplyState = ref(false)
const commentContent = ref('')
const toggleLocalReply = () => {
  localReplyState.value = !localReplyState.value
  if (localReplyState.value) {
    parentId.value = props.comment.id
  }
}


// 从父组件注入的localReplyClick响应式变量，用于控制是否执行回复操作
const localReplyClick = inject('localReplyClick') as Ref<boolean>
const parentId = inject('parentId') as Ref<number | undefined>
const refreshComments = inject('refreshComments') as () => Promise<void>

const deleteReply = async () => {
  try {
    const res = await deleteCommentUsingPost({ commentId: props.comment.id })
    if (res.data.code === 0) {
      message.success('评论删除成功')
      await refreshComments() // 刷新评论列表
    } else {
      message.error('评论删除失败，' + res.data.message)
    }
  } catch (e) {
    message.error('评论删除失败：' + (e as Error).message)
  }
}

// 发布评论
const addComment = async () => {
  if (!commentContent.value) {
    message.warning('请输入评论内容')
    return
  }
  try {
    const res = await createCommentUsingPost({
      pictureId: props.comment.pictureId,
      userId: loginUserStore.loginUser?.id,
      content: commentContent.value,
      parentId: parentId.value // 添加 parentId 参数
    })
    if (res.data.code === 0) {
      message.success('评论成功')
      commentContent.value = ''
      parentId.value = undefined // 重置 parentId
      localReplyClick.value = true // 重置 localReplyClick
      await refreshComments() // 刷新评论列表
    } else {
      message.error('评论失败，' + res.data.message)
    }
  } catch (e) {
    message.error('评论失败：' + (e as Error).message)
  }
}
// 监听 localReplyClick 的变化
watch(localReplyClick, (newValue) => {
  if (newValue) {
    console.log('执行回复操作' + newValue)
    localReplyState.value = false // 重置 localReplyClick
  }
})
</script>

<style scoped>
.reply-box {
  margin-left: 24px;
}
</style>
